package com.app.controller.importExcel;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.common.AdminPermissionImportTableAnalysisEventListener;
import com.app.mapper.YearTaskMapper;
import com.app.model.*;
import com.app.service.AdminUserService;
import com.app.service.AmmunitionService;
import com.app.service.DepartmentService;
import com.app.service.PlantService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.YearTaskVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 导入 后勤
 */
@Slf4j
@RestController
@Controller
@RequestMapping("/api/import")
public class ImportLogisticsController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private AmmunitionService ammunitionService;
    @Autowired
    private PlantService plantService;
    @Autowired
    private YearTaskMapper yearTaskMapper;

    //导入弹药检测统计信息
    @PostMapping("/importAmmunition")
    public Result<Object> importAmmunition(MultipartFile file, HttpServletRequest request) throws Exception {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("序号", "number");
        reader.addHeaderAlias("任务类型", "taskType");
        reader.addHeaderAlias("型号", "type");
        reader.addHeaderAlias("日期（检测时间）", "detectionTime");
        reader.addHeaderAlias("工作时间", "workTime");
        reader.addHeaderAlias("检测数量", "detectionNumber");
        reader.addHeaderAlias("责任单位", "department");
        //reader.read(标头行数，开始行数，对象)
        List<AmmunitionModel> ammunitionModels = reader.read(1, 2, AmmunitionModel.class);
        for (int i = 0; i < ammunitionModels.size(); i++) {
            AmmunitionModel ammunitionModel = ammunitionModels.get(i);
            if (StrUtil.isNotBlank(ammunitionModel.getWorkTime())) {
                List<String> workTimeList = new ArrayList<>(Arrays.asList(ammunitionModel.getWorkTime().split("-")));
                if (!workTimeList.isEmpty()) {
                    ammunitionModel.setWorkTime(JSON.toJSONString(workTimeList));
                } else {
                    ammunitionModel.setWorkTime("[]");
                }

            }
            ammunitionModel.setCreateTime(CommonHelp.getNowTimestamp());
            ammunitionService.insert(ammunitionModel);
        }
        return Result.success("");
    }

    //技术厂房阵地
    @PostMapping("/importPlant")
    public Result<Object> importPlant(MultipartFile file, HttpServletRequest request) throws Exception {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("位置", "position");
        reader.addHeaderAlias("型号", "model");
        reader.addHeaderAlias("类型", "type");
        reader.addHeaderAlias("数量", "number");
        reader.addHeaderAlias("所属单位", "departmentName");
        reader.addHeaderAlias("负责人", "personName");
        reader.addHeaderAlias("有无战斗部", "isXxText");
        reader.addHeaderAlias("有无真实发动机", "isEngineText");
        reader.addHeaderAlias("入库日期", "warehousingDate");
        reader.addHeaderAlias("出库日期", "deliveryDate");
        reader.addHeaderAlias("用途", "useTo");
        reader.addHeaderAlias("备注", "remark");
        //reader.read(标头行数，开始行数，对象)
        List<PlantModel> plantModelList = reader.read(3, 4, PlantModel.class);
        for (PlantModel plantModel : plantModelList) {
            if (plantModel.getIsXxText() != null && plantModel.getIsXxText().equals("有")) {
                plantModel.setIsXx(1);
            } else {
                plantModel.setIsXx(0);
            }
            if (plantModel.getIsEngineText() != null && plantModel.getIsEngineText().equals("有")) {
                plantModel.setIsEngine(1);
            } else {
                plantModel.setIsEngine(0);
            }
            plantModel.setCreateTime(CommonHelp.getNowTimestamp());
            plantService.insert(plantModel);
        }
        return Result.success("");
    }

    @PostMapping("/importYearTask")
    @Transactional
    public Result importPermissionTableV1(@RequestParam("file") MultipartFile file, @RequestParam("year") String year, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<YearTaskModel> permissionList = new ArrayList<>();
        try {
            AdminPermissionImportTableAnalysisEventListener listener = new AdminPermissionImportTableAnalysisEventListener();
            EasyExcel.read(file.getInputStream(), YearTaskModel.class, listener).extraRead(CellExtraTypeEnum.MERGE).sheet().doRead();
            permissionList = listener.getList();
            //todo check-->do--->save--->result
            for (YearTaskModel yearTaskModel : permissionList) {
                yearTaskModel.setYear(year);
                yearTaskModel.setCreateTime(CommonHelp.getNowTimestamp());
                yearTaskMapper.insert(yearTaskModel);
            }
        } catch (IOException e) {
            e.printStackTrace();
//            throw new IllegalArgumentException(e.getMessage());
            return Result.error(500, "导入失败");
        }
        return Result.success("导入成功");
    }

    /**
     * 年度任务列表
     *
     * @param page             第页
     * @param limit            限制
     * @param year             年份
     * @param completionStatus 完成状态
     * @return {@link Result}
     */
    @GetMapping("/yearTaskList")
    public Result yearTaskList(Integer page, Integer limit, String year, String completionStatus, Integer sortType,HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        Page<YearTaskModel> yearTaskModelPage = new Page<>(page, limit);
        QueryWrapper<YearTaskModel> yearTaskModelQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(year)) {
            yearTaskModelQueryWrapper.eq("year", year);
        }
        if (completionStatus != null) {
            yearTaskModelQueryWrapper.eq("completion_status", completionStatus);
        }
        if (sortType==null || sortType==1){
            yearTaskModelQueryWrapper.orderByAsc("number");
        }else {
            yearTaskModelQueryWrapper.orderByDesc("number");
        }

        Page<YearTaskModel> yearTaskModelPage1 = yearTaskMapper.selectPage(yearTaskModelPage, yearTaskModelQueryWrapper);
        List<YearTaskModel> yearTaskModelList = yearTaskModelPage1.getRecords();
        YearTaskVo vo = new YearTaskVo();
        vo.setList(yearTaskModelList);
        vo.setCount((int) yearTaskModelPage1.getTotal());
        return Result.success(vo);
    }

    /**
     * 年度任务更新状态
     *
     * @param id               id
     * @param completionStatus 完成状态
     * @param completionText   完成文本
     * @return {@link Result}
     */
    @GetMapping("/yearTaskUpdateStatus")
    public Result yearTaskUpdateStatus(Integer id, String completionStatus, String completionText, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        YearTaskModel yearTaskModel = yearTaskMapper.selectById(id);
        if (completionStatus != null) {
            yearTaskModel.setCompletionStatus(completionStatus);
            yearTaskModel.setCompletionText(completionText);
            yearTaskMapper.updateById(yearTaskModel);
        }
        return Result.success("操作成功");
    }

    /**
     * 年任务详细信息
     *
     * @param id id
     * @return {@link Result}
     */
    @GetMapping("/yearTaskDetail")
    public Result yearTaskDetail(Integer id, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        return Result.success(yearTaskMapper.selectById(id));
    }
}
